<template>
    <div class="header-search">
        <el-icon class="search-icon" @click.stop="onShow">
            <Search />
        </el-icon>
        <el-select v-model="searchValue" filterable placeholder="搜索" 
        class="header-search-select" :class="{show:isShow}" :remote="true"
        :remote-method="querySearch"
        @change="optionChange"
        ref="input"
        >
            <el-option v-for="item in searchOption" :value="item.item" :label="item.item.titles.join(' > ')" :key="item.item.path">
            </el-option>
        </el-select>
    </div>
</template>

<script setup>
// 搜索框
import { ref,watch } from 'vue';
import {useRouter} from 'vue-router'
import optionData  from '@/assets/js/handleData'
import Fuse from 'fuse.js'
const searchValue = ref({})
const isShow = ref(false)
const router = useRouter()
const input = ref({})

const onShow = ()=>{ // 展开关闭搜索框
    input.value.focus()
    isShow.value = !isShow.value
}
const searchOption = ref([])
const querySearch = (query)=>{ // 自定义筛选方法
    searchOption.value = fuse.search(query)
}

const pool = optionData()
// 初始化fuse
const fuse = new Fuse(pool,{
    // 是否按照优先级排序
    shouldSort:true,
    // 分配权重
    keys:[
        {name:'title',weight:0.7},
        {name:'path',weight:0.3}
    ]
})

// 监听路由地址的选择，进行路由跳转
const optionChange = (val)=>{
    router.push(val.path)
    isShow.value = false
    searchOption.value = []
    searchValue.value = null
}

const CloseInput = ()=>{
    isShow.value = false
}

// 点击任何位置都可以收起input框
watch(isShow,()=>{
    if(isShow.value){
        document.addEventListener('click',CloseInput)
    }else{
        document.removeEventListener('click',CloseInput)
    }
})

</script>


<style lang="scss" scoped>
.header-search {
    font-size: 0 !important;
    
    .search-icon {
        cursor: pointer;
        font-size: 18px;
        vertical-align: middle;
    }
.header-search-select{
    transition: width 0.4s;
    width: 0;
    overflow: hidden;

    outline: none;
    &.show{
        width: 210px;
    } 
}
}
</style>